package com.toutiao.score

import javax.servlet.http.{HttpServlet,HttpServletRequest,HttpServletResponse}
import net.liftweb.json.{JsonAST,Extraction,Printer,parse}

class ExpServlet(s:ScoreFeaturer) extends HttpServlet {
  
  private
  val scorer = s
  
  implicit val _ = net.liftweb.json.DefaultFormats
  
  def process(rq:HttpServletRequest, rp:HttpServletResponse):Unit = {
    rp.setContentType("text/html")
    rp.setCharacterEncoding("utf-8")
    rq.setCharacterEncoding("utf-8")
    
    val cutTitle = rq.getParameter("title")
    val cutContent = rq.getParameter("content")
    val score = rq.getParameter("score")
    
    val m = 
      score match {
      case "1" => scorer.score1(cutTitle, cutContent)
      case "2" => scorer.score2(cutTitle, cutContent)
      case "3" => scorer.score3(cutTitle, cutContent)
      case "4" => scorer.score4(cutTitle, cutContent)
    }
    
    val data = Printer.compact(JsonAST.render(Extraction.decompose(m)))
    
    rp.getWriter.print(data)
    
  }
  
  override
  def doGet(rq:HttpServletRequest, rp:HttpServletResponse):Unit = {
    process(rq,rp)
  }
  
  override
  def doPost(rq:HttpServletRequest, rp:HttpServletResponse):Unit = {
    process(rq,rp)
  }

}

class SimServlet(s:SimScorer) extends HttpServlet {
  
  private
  val scorer = s
  
  implicit val _ = net.liftweb.json.DefaultFormats
  
  def process(rq:HttpServletRequest, rp:HttpServletResponse):Unit = {
    rp.setContentType("text/html")
    rp.setCharacterEncoding("utf-8")
    rq.setCharacterEncoding("utf-8")
    
    val cutTitle1 = rq.getParameter("title1")
    val cutContent1 = rq.getParameter("content1")
    val cutTitle2 = rq.getParameter("title2")
    val cutContent2 = rq.getParameter("content2")
    
    val sim = s.getSimScore(cutTitle1, cutContent1, cutTitle2, cutContent2)
    
    val data = Printer.compact(JsonAST.render(Extraction.decompose(sim)))
    
    rp.getWriter.print(data)
  }
  
  override
  def doGet(rq:HttpServletRequest, rp:HttpServletResponse):Unit = {
    process(rq,rp)
  }
  
  override
  def doPost(rq:HttpServletRequest, rp:HttpServletResponse):Unit = {
    process(rq,rp)
  }  
  
}